<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>报工提交-会员中心 - 工厂报工系统</title>
{include file="common/header"}
<div class="max-w-lg mx-auto bg-white rounded shadow p-6 mt-8">
  <h2 class="text-xl font-bold mb-4 text-blue-600">报工</h2>
  {if isset($error) && $error}
    <div class="mb-4 p-3 bg-red-100 text-red-700 rounded text-center text-base font-bold">{$error}</div>
  {/if}
  {if isset($success) && $success}
    <div class="mb-4 p-3 bg-green-100 text-green-700 rounded text-center text-base font-bold">{$success}</div>
  {/if}
  <!-- 调试用：打印当前 allocation_id -->
  <script>console.log('页面分配ID：', '{$allocation.id|default="无"}');</script>
  <script>console.log('产品编号数量：', '{$productItems|count}');</script>
  <script>console.log('产品编号列表：', JSON.parse('{$productItems|json_encode}'));</script>
  {if isset($allocation) && $allocation}
    <div class="mb-4 p-4 bg-gray-50 rounded">
      <div class="mb-1 text-sm text-gray-700 font-medium">任务信息：</div>
      <div class="text-sm text-gray-800 mb-1">订单号：<span class="font-bold">{$allocation.order_no}</span></div>
      <div class="text-sm text-gray-800 mb-1">产品：<span class="font-bold">{$allocation.product_name}</span></div>
      <div class="text-sm text-gray-800 mb-1">型号：<span class="font-bold">{$allocation.model_name}</span></div>
      <div class="text-sm text-gray-800 mb-1">工序：<span class="font-bold">{$allocation.process_name}</span></div>
      <div class="text-sm text-gray-800 mb-1">分配数量：<span class="font-bold">{$allocation.quantity}</span></div>
      <div class="text-sm text-gray-800 mb-1">已报：<span class="font-bold">{$allocation.reported_quantity}</span></div>
      <div class="text-sm text-gray-800">待报：<span class="font-bold text-primary">{$allocation.remaining_quantity}</span></div>
    </div>
    <form method="post" action="/index/worker/report" enctype="multipart/form-data" class="space-y-4" id="reportForm">
      <input type="hidden" name="allocation_id" value="{$allocation.id}" />
      
      <!-- 工作类型选择 -->
      <div>
        <label class="block mb-1 font-medium">工作类型</label>
        <select name="work_type" id="work_type" class="w-full border rounded px-3 py-2" onchange="toggleWorkType()">
          <option value="piece">计件</option>
          <option value="time">计时</option>
        </select>
      </div>
      
      <!-- 计件工作 - 产品编号选择 -->
      <div id="piece_work" class="work-type-section">
        <label class="block mb-1 font-medium">选择产品编号</label>
        <div class="border rounded p-3 bg-gray-50 max-h-40 overflow-y-auto">
          {if isset($productItems) && $productItems}
            {volist name="productItems" id="item"}
              <div class="product-item-block mb-3 p-2 border rounded" data-item-no="{$item.item_no}">
                <label class="block mb-2">
                  <input type="checkbox" name="item_nos[]" value="{$item.item_no}" class="mr-2 item-checkbox" onchange="toggleItemImages('{$item.item_no}')">
                  <span class="text-sm font-medium">{$item.item_no}</span>
                </label>
                <!-- 每个产品编号的图片上传区域 -->
                <div class="item-images-section" id="images_{$item.item_no}" style="display:none;">
                  <div class="text-xs text-gray-600 mb-1">为 {$item.item_no} 上传图片（最多9张，单张≤10M）</div>
                  <!-- 隐藏的文件输入框 -->
                  <input type="file" name="item_images[{$item.item_no}][]" accept="image/*" multiple class="form-control" style="display:none;" id="fileInput_{$item.item_no}" onchange="addItemImages(this, '{$item.item_no}')">
                  <!-- 添加图片按钮 -->
                  <button type="button" class="btn btn-sm btn-primary mb-2" onclick="document.getElementById('fileInput_{$item.item_no}').click()">
                    📷 添加图片
                  </button>
                  <!-- 文件数量显示 -->
                  <div class="text-xs text-gray-500 mb-1">已选择 <span id="fileCount_{$item.item_no}">0</span> 张图片</div>
                  <div class="item-preview" id="preview_{$item.item_no}" class="d-flex flex-wrap mt-2"></div>
                </div>
              </div>
            {/volist}
          {else}
            <p class="text-sm text-gray-500">暂无可报工的产品编号</p>
          {/if}
        </div>
        <p class="text-xs text-gray-500 mt-1">已选择 <span id="selected_count">0</span> 个产品编号</p>
      </div>
      
      <!-- 计时工作 - 工时输入 -->
      <div id="time_work" class="work-type-section" style="display:none;">
        <label class="block mb-1 font-medium">工时（小时）</label>
        <input type="number" name="work_hours" step="0.5" min="0.5" class="w-full border rounded px-3 py-2" />
        <p class="text-xs text-gray-500 mt-1">请输入工作小时数</p>
      </div>
      <div>
        <label class="block mb-1 font-medium">备注</label>
        <input type="text" name="remark" class="w-full border rounded px-3 py-2" placeholder="可选" />
      </div>
      <!-- 计时工作的图片上传区域 -->
      <div id="time_images" class="work-type-section" style="display:none;">
      <div class="form-group">
        <label>上传完工图片（最多9张，单张≤10M）</label>
        <input type="file" name="images[]" id="images" accept="image/*" multiple class="form-control" style="max-width:100%;">
        <div id="preview" class="d-flex flex-wrap mt-2"></div>
        </div>
      </div>
      <script>
        const maxFiles = 9;
        const maxSize = 10 * 1024 * 1024; // 10M
        const input = document.getElementById('images');
        input && input.addEventListener('change', function(e){
          const preview = document.getElementById('preview');
          preview.innerHTML = '';
          let files = Array.from(this.files);
          if(files.length > maxFiles) {
            alert('最多只能上传9张图片');
            this.value = '';
            return;
          }
          files.forEach((file, idx) => {
            if(file.size > maxSize) {
              alert('图片不能超过10M');
              this.value = '';
              preview.innerHTML = '';
              return;
            }
            let reader = new FileReader();
            reader.onload = function(ev){
              let div = document.createElement('div');
              div.className = 'position-relative m-1';
              div.style.width = '90px';
              div.style.height = '90px';
              div.innerHTML = `<img src="${ev.target.result}" class="img-fluid rounded border" style="width:100%;height:100%;object-fit:cover;">
                <button type="button" class="btn btn-sm btn-danger position-absolute" style="top:2px;right:2px;z-index:2;" onclick="removeImage(${idx})">×</button>`;
              preview.appendChild(div);
            };
            reader.readAsDataURL(file);
          });
        });
        function removeImage(idx){
          let input = document.getElementById('images');
          let dt = new DataTransfer();
          let files = Array.from(input.files);
          files.splice(idx, 1);
          files.forEach(f => dt.items.add(f));
          input.files = dt.files;
          input.dispatchEvent(new Event('change'));
        }
        // 切换产品编号图片上传区域显示
        function toggleItemImages(itemNo) {
          const checkbox = document.querySelector(`input[value="${itemNo}"]`);
          const imagesSection = document.getElementById(`images_${itemNo}`);
          if (checkbox.checked) {
            imagesSection.style.display = 'block';
          } else {
            imagesSection.style.display = 'none';
            // 清空预览
            document.getElementById(`preview_${itemNo}`).innerHTML = '';
            // 清空文件选择
            imagesSection.querySelector('input[type="file"]').value = '';
            // 清空文件列表
            if (itemFiles[itemNo]) {
              itemFiles[itemNo] = [];
              document.getElementById(`fileCount_${itemNo}`).textContent = '0';
            }
          }
        }
        
        // 存储每个产品编号的文件
        const itemFiles = {};
        
        // 添加产品编号的图片
        function addItemImages(input, itemNo) {
          if (!itemFiles[itemNo]) {
            itemFiles[itemNo] = [];
          }
          
          const newFiles = Array.from(input.files);
          const maxFiles = 9;
          const maxSize = 10 * 1024 * 1024; // 10M
          
          // 检查总数限制
          if (itemFiles[itemNo].length + newFiles.length > maxFiles) {
            alert('最多只能选择9张图片！');
            input.value = '';
            return;
          }
          
          // 检查文件大小
          for (let file of newFiles) {
            if (file.size > maxSize) {
              alert('图片不能超过10M');
              input.value = '';
              return;
            }
          }
          
          // 添加新文件到列表
          itemFiles[itemNo] = itemFiles[itemNo].concat(newFiles);
          
          // 更新文件计数
          document.getElementById(`fileCount_${itemNo}`).textContent = itemFiles[itemNo].length;
          
          // 更新预览
          updateItemPreview(itemNo);
          
          // 清空input，允许重复选择
          input.value = '';
        }
        
        // 更新产品编号的图片预览
        function updateItemPreview(itemNo) {
          const preview = document.getElementById(`preview_${itemNo}`);
          preview.innerHTML = '';
          
          if (!itemFiles[itemNo]) return;
          
          itemFiles[itemNo].forEach((file, idx) => {
            let reader = new FileReader();
            reader.onload = function(ev){
              let div = document.createElement('div');
              div.className = 'position-relative m-1';
              div.style.width = '90px';
              div.style.height = '90px';
              div.innerHTML = `<img src="${ev.target.result}" class="img-fluid rounded border" style="width:100%;height:100%;object-fit:cover;">
                <button type="button" class="btn btn-sm btn-danger position-absolute" style="top:2px;right:2px;z-index:2;" onclick="removeItemImage('${itemNo}', ${idx})">×</button>`;
              preview.appendChild(div);
            };
            reader.readAsDataURL(file);
          });
        }
        
        // 移除产品编号的图片
        function removeItemImage(itemNo, idx) {
          if (itemFiles[itemNo]) {
            itemFiles[itemNo].splice(idx, 1);
            document.getElementById(`fileCount_${itemNo}`).textContent = itemFiles[itemNo].length;
            updateItemPreview(itemNo);
          }
        }
        
                // 工作类型切换
        function toggleWorkType() {
          const workType = document.getElementById('work_type').value;
          const pieceWork = document.getElementById('piece_work');
          const timeWork = document.getElementById('time_work');
          const timeImages = document.getElementById('time_images');
          
          if (workType === 'piece') {
            pieceWork.style.display = 'block';
            timeWork.style.display = 'none';
            timeImages.style.display = 'none';
          } else {
            pieceWork.style.display = 'none';
            timeWork.style.display = 'block';
            timeImages.style.display = 'block';
          }
        }
        
        // 产品编号选择计数
        document.addEventListener('DOMContentLoaded', function() {
          const checkboxes = document.querySelectorAll('.item-checkbox');
          const selectedCount = document.getElementById('selected_count');
          
          checkboxes.forEach(function(checkbox) {
            checkbox.addEventListener('change', function() {
              const checkedCount = document.querySelectorAll('.item-checkbox:checked').length;
              selectedCount.textContent = checkedCount;
            });
          });
        });
        
        // 表单提交时处理多次选择的图片
        document.addEventListener('DOMContentLoaded', function() {
          var reportForm = document.getElementById('reportForm');
          if (reportForm) {
            reportForm.addEventListener('submit', function(e){
              // 阻止默认提交
              e.preventDefault();
              
              // 创建新的FormData
              var formData = new FormData();
              
              // 添加基本字段
              var form = this;
              var basicFields = ['allocation_id', 'work_type', 'work_hours', 'remark'];
              basicFields.forEach(function(field) {
                var input = form.querySelector('[name="' + field + '"]');
                if (input && input.value) {
                  formData.append(field, input.value);
                }
              });
              
              // 添加选中的产品编号
              var selectedItems = document.querySelectorAll('.item-checkbox:checked');
              selectedItems.forEach(function(checkbox) {
                formData.append('item_nos[]', checkbox.value);
              });
              
              // 添加计时工作的图片
              var timeImages = document.getElementById('images');
              if (timeImages && timeImages.files.length > 0) {
                for (var i = 0; i < timeImages.files.length; i++) {
                  formData.append('images[]', timeImages.files[i]);
                }
              }
              
              // 添加计件工作的图片
              if (typeof itemFiles !== 'undefined') {
                for (var itemNo in itemFiles) {
                  if (itemFiles[itemNo] && itemFiles[itemNo].length > 0) {
                    itemFiles[itemNo].forEach(function(file) {
                      formData.append('item_images[' + itemNo + '][]', file);
                    });
                  }
                }
              }
              
              // 打印提交信息
              var log = {};
              for(let [k,v] of formData.entries()){
                if(k.includes('images[]') || k.includes('item_images')){
                  if(!log[k]) log[k] = [];
                  log[k].push(v.name);
                }else{
                  log[k] = v;
                }
              }
              console.log('报工表单提交字段：', log);
              
              // 提交表单
              fetch(form.action, {
                method: 'POST',
                body: formData
              })
              .then(response => response.text())
              .then(data => {
                console.log('提交成功:', data);
                // 如果返回的是HTML页面，说明提交成功，刷新页面
                if (data.includes('报工提交成功')) {
                  alert('报工提交成功！');
                  window.location.reload();
                } else {
                  // 显示返回的内容
                  document.body.innerHTML = data;
                }
              })
              .catch(error => {
                console.error('提交失败:', error);
                alert('提交失败: ' + error.message);
              });
            });
          }
        });
      </script>
      <button type="submit" class="w-full bg-blue-600 text-white py-2 rounded font-bold hover:bg-blue-700">提交报工</button>
    </form>
  {else}
    <div class="text-center text-red-600 font-bold py-8">
      未找到任务信息，请通过任务列表进入报工页面，或联系管理员！
    </div>
  {/if}
</div>
<script>
// 使用原生JavaScript，避免require依赖问题
document.addEventListener('DOMContentLoaded', function() {
    // 产品编号选择计数
    var checkboxes = document.querySelectorAll('.item-checkbox');
    var selectedCount = document.getElementById('selected_count');
    
    checkboxes.forEach(function(checkbox) {
        checkbox.addEventListener('change', function() {
            var checkedCount = document.querySelectorAll('.item-checkbox:checked').length;
            selectedCount.textContent = checkedCount;
        });
    });
    
    // 工作类型切换
    var workTypeSelect = document.getElementById('work_type');
    if (workTypeSelect) {
        workTypeSelect.addEventListener('change', function() {
            var workType = this.value;
            var pieceWork = document.getElementById('piece_work');
            var timeWork = document.getElementById('time_work');
            var timeImages = document.getElementById('time_images');
            
            if (workType === 'piece') {
                pieceWork.style.display = 'block';
                timeWork.style.display = 'none';
                timeImages.style.display = 'none';
            } else {
                pieceWork.style.display = 'none';
                timeWork.style.display = 'block';
                timeImages.style.display = 'block';
            }
        });
    }
});
</script>
{include file="common/footer"}
